package cn.itlaobing;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;


import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * ClassName: Doem01 <br/>
 * Function:maven项目练习<br/>
 * date: 2017年10月30日 下午3:24:40 <br/>
 * 
 * @author 王博
 * @version
 * @since JDK 1.8
 */
public class Doem01 {
	public static void main(String[] args){
		OkHttpClient client = new OkHttpClient();

		String url = "http://pvp.qq.com";
		Request request = new Request.Builder().url(url).build();
		String source=null;
		try {
			Response response = client.newCall(request).execute();
			source = response.body().string();
		} catch (IOException e) {
			System.out.println("OkHTTP出现异常");
		}

		// 创建正则表达式
		String reg = "<img(.*?)/>";
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(source);
		Boolean rs = null;
		ArrayList<String> strs = new ArrayList<String>();
		while (matcher.find()) {
			strs.add(matcher.group());
		}
		for (String s : strs) {
			try {
				zol(s.substring(10, s.length()-3));
			} catch (IOException e) {
				System.out.println("图片下载失败");
			}
		}
		System.out.println("下载完成");
	}
	/** 
	 * zol:(读取图片). <br/>
	 * 
	 * @author 王博 
	 * @param source
	 * @throws IOException 
	 * @since JDK 1.8 
	 */  
	private static void zol(String source) throws IOException {
		if(!source.startsWith("http:")) {
			source="http:"+source;
		}
		//new一个url对象
		URL url=new URL(null,source,new sun.net.www.protocol.https.Handler());
		//打开连接
		HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
		//设置请求方式
		conn.setRequestMethod("GET");
		//超时响应时间
		conn.setConnectTimeout(5*1000);
		//通过输入流获取图片数据
		InputStream is=conn.getInputStream();
		//得到图片二进制数据
		byte[] data=readInputStream(is);
		Date date=new Date();
		long s=date.getTime();
		String file="F:\\pos\\"+s+".jpg";
		File imageFile = new File(file);  
        //创建输出流  
        FileOutputStream outStream = new FileOutputStream(imageFile);  
        //写入数据  
        outStream.write(data);
        outStream.close();
	}
	/** 
	 * readInputStream:(读取图片数据). <br/>
	 * 
	 * @author 王博 
	 * @param is
	 * @return 
	 * @throws IOException 
	 * @since JDK 1.8 
	 */  
	private static byte[] readInputStream(InputStream is) throws IOException {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
		byte[] data= new byte[2048];
		BufferedInputStream bis=new BufferedInputStream(is);
		int length=-1;
		while((length=bis.read(data))!=-1) {
			outStream.write(data, 0, length);  
		}
		bis.close();
		outStream.close();
		return outStream.toByteArray();
	}
	
	
	
}
